package com.yiba.vpn.util;

import javax.persistence.criteria.CriteriaBuilder;
import javax.transaction.Synchronization;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 根据服务器地址生成不重复的端口
 *
 * @author zws
 */
public class NodeHostPortUtils {

    private final static int NODE_PORT_START_NUM=20000;

    private final static int NODE_PORT_EXTEND_NUM=40000;

    //存放host 跟对应的端口集合
    private static  HashMap<String,List<Integer>> map =new HashMap<>();

    // 根据host 查询端口是否存在
    public   static  Integer createPortByHostAndAlreadyHasPorts(List<Integer> ports) {
        int num = 0;
        Integer pp = createPort(ports);
        return pp;
    }

    // 根据host 查询端口是否存在
    public   static  Integer createPortByHostAndAlreadyHasPortsBylocalCache(String host) {

        List<Integer> ports =map.get(""+host);
        if(ports ==null){
            //表示这个host 的端口信息本地没有缓存去数据库查一下
            return -1;
        }
        Integer pp =  createPort(ports);

        ports.add(pp);

        map.put(""+host,ports);

        return pp;
    }

    // 根据host 查询端口是否存在
    public   static  Integer createPortByHostAndAlreadyHasPortsBylocalCache(String host, List<Integer> ports) {
        int num = 0;
        Integer pp =   createPort(ports);

        ports.add(pp);

        map.put(""+host,ports);

        return pp;
    }

    //根据host 删除port
    public   static  boolean deletePortByHost(String host, Integer prot) {
        List<Integer> ports =map.get(""+host);
        if(ports ==null){
            //表示这个host 的端口信息
            return true;
        }

        ports.remove(prot);

        map.put(""+host,ports);

        return true;
    }


    private  static  Integer  createPort(List<Integer> ports) {
        Random rand = new Random();
        Integer pp =  rand.nextInt(NODE_PORT_START_NUM)+NODE_PORT_EXTEND_NUM;

        int num = 0;

        if (ports != null && ports.size() > 0) {

            while (ports.contains(pp)) {
                pp = createPort();
                num++;
                //防止这个服务IP 被全部生成了
                if (num >= 20000) {
                    break;
                }
            }
        }
        return  pp;
    }

    //随机生成区间的端口号
    private static Integer  createPort() {

        Random rand = new Random();
        Integer pp =  rand.nextInt(NODE_PORT_START_NUM)+NODE_PORT_EXTEND_NUM;
        return  pp;
    }



}
